jQuery(document).ready(function($) {
    // 初始化图表
    function initCharts() {
        const startDate = $('#bda-start-date').val();
        const endDate = $('#bda-end-date').val();

        // 获取销售数据
        $.ajax({
            url: bdaDashboard.api_url,
            method: 'GET',
            data: {
                start_date: startDate,
                end_date: endDate
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', bdaDashboard.nonce);
            },
            success: function(response) {
                renderSalesChart(response.sales);
            }
        });

        // 获取用户画像数据
        $.ajax({
            url: bdaDashboard.segments_url,
            method: 'GET',
            data: {
                start_date: startDate,
                end_date: endDate
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader('X-WP-Nonce', bdaDashboard.nonce);
            },
            success: function(response) {
                renderUserSegmentsChart(response.analysis);
                renderUserSegmentsDetails(response.analysis);
            }
        });
    }

    // 渲染销售图表
    function renderSalesChart(data) {
        const ctx = document.getElementById('sales-chart').getContext('2d');
        
        if (window.salesChart) {
            window.salesChart.destroy();
        }
        
        window.salesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(item => item.date),
                datasets: [{
                    label: '销售额',
                    data: data.map(item => item.revenue),
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return '销售额: ' + context.parsed.y.toFixed(2);
                            }
                        }
                    }
                }
            }
        });
    }

    // 渲染用户画像图表
    function renderUserSegmentsChart(data) {
        const ctx = document.getElementById('user-segments-chart').getContext('2d');
        
        if (window.segmentsChart) {
            window.segmentsChart.destroy();
        }
        
        // 准备数据
        const segmentData = {
            labels: ['高价值用户', '中等价值用户', '低价值用户'],
            datasets: [{
                label: '用户数量',
                data: [data.high_value, data.medium_value, data.low_value],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)'
                ],
                borderWidth: 1
            }]
        };
        
        window.segmentsChart = new Chart(ctx, {
            type: 'bar',
            data: segmentData,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
    
    // 渲染用户画像详情
    function renderUserSegmentsDetails(data) {
        let html = `
            <div class="segment-row">
                <span class="segment-label">总用户数:</span>
                <span class="segment-value">${data.total_users}</span>
            </div>
            <div class="segment-row">
                <span class="segment-label">高价值用户:</span>
                <span class="segment-value">${data.high_value}</span>
            </div>
            <div class="segment-row">
                <span class="segment-label">中等价值用户:</span>
                <span class="segment-value">${data.medium_value}</span>
            </div>
            <div class="segment-row">
                <span class="segment-label">低价值用户:</span>
                <span class="segment-value">${data.low_value}</span>
            </div>
        `;
        
        // 添加热门类别
        html += '<h4>热门商品类别</h4>';
        for (const [cat_id, count] of Object.entries(data.categories)) {
            html += `
                <div class="segment-row">
                    <span class="segment-label">类别 ${cat_id}:</span>
                    <span class="segment-value">${count} 用户</span>
                </div>
            `;
        }
        
        // 添加地理分布
        html += '<h4>用户地理分布</h4>';
        for (const [country, count] of Object.entries(data.geography)) {
            html += `
                <div class="segment-row">
                    <span class="segment-label">${country}:</span>
                    <span class="segment-value">${count} 用户</span>
                </div>
            `;
        }
        
        $('#user-segments-details').html(html);
    }
    
    // 导出报告
    function exportReport() {
        const startDate = $('#bda-start-date').val();
        const endDate = $('#bda-end-date').val();
        
        // 显示导出选项对话框
        const exportType = prompt("请选择导出格式 (输入 'pdf' 或 'csv'):", "pdf");
        
        if (exportType && (exportType.toLowerCase() === 'pdf' || exportType.toLowerCase() === 'csv')) {
            // 显示加载状态
            const exportBtn = $('#bda-export-report');
            const originalText = exportBtn.text();
            exportBtn.text('导出中...').prop('disabled', true);
            
            $.ajax({
                url: bdaDashboard.export_url,
                method: 'POST',
                data: {
                    start_date: startDate,
                    end_date: endDate,
                    export_type: exportType.toLowerCase()
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', bdaDashboard.nonce);
                },
                dataType: 'json', // 确保期望JSON响应
                success: function(response) {
                    if (response.success) {
                        if (response.type === 'pdf') {
                            // 处理PDF下载
                            const byteCharacters = atob(response.content);
                            const byteNumbers = new Array(byteCharacters.length);
                            for (let i = 0; i < byteCharacters.length; i++) {
                                byteNumbers[i] = byteCharacters.charCodeAt(i);
                            }
                            const byteArray = new Uint8Array(byteNumbers);
                            const blob = new Blob([byteArray], {type: 'application/pdf'});
                            const link = document.createElement('a');
                            link.href = window.URL.createObjectURL(blob);
                            link.download = response.filename;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        } else {
                            // 处理CSV下载
                            const blob = new Blob([response.content], { type: 'text/csv;charset=utf-8;' });
                            const link = document.createElement('a');
                            link.href = URL.createObjectURL(blob);
                            link.download = response.filename;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }
                    } else {
                        alert('导出失败: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    try {
                        // 尝试解析错误响应
                        const errorResponse = JSON.parse(xhr.responseText);
                        if (errorResponse.message) {
                            alert('导出报告失败: ' + errorResponse.message);
                        } else {
                            alert('导出报告失败: ' + error);
                        }
                    } catch (e) {
                        alert('导出报告失败: ' + error + '\n响应: ' + xhr.responseText);
                    }
                },
                complete: function() {
                    exportBtn.text(originalText).prop('disabled', false);
                }
            });
        } else if (exportType !== null) {
            alert('请输入有效的导出格式 (pdf 或 csv)');
        }
    }

    // 绑定事件
    $('#bda-update-charts').click(initCharts);
    $('#bda-export-report').click(exportReport);

    // 首次加载
    initCharts();
});